package com.zj.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 文件类型校验器
 */
public class FileTypeValidator {
    /**
     * 允许上传的文件MIME类型(http协议中定义的文件类型)
     */
    //将一个数组转换（或者说“包装”）成一个固定大小的 List。
    private static final Set<String> ALLOWED_FILE_TYPES =new HashSet<>(Arrays.asList(
            "image/jpeg","image/png","image/gif",
            "application/pdf"
            ,"application/msword" //.doc
            ,"application/vnd.ms-excel" //.xls
            ,"application/vnd.openxmlformats-officedocument.wordprocessingml.document" //.docx
            ,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" //.xlsx
    ));

    /**
     * 允许上传的文件后缀名
     */
    private static final Set<String> ALLOWED_FILE_EXTENSIONS =new HashSet<>(Arrays.asList(
            "jpg","jpeg","png","gif","pdf","doc","docx","xls","xlsx"
    ));

    /**
     * 校验文件类型是否被允许
     * @param contentType 文件类型
     * @param fileName 文件名
     * @return true：被允许；false：不被允许
     */
    public static boolean isAllowedFileType(String contentType,String fileName){
        if(contentType==null||fileName==null||fileName.isEmpty()||contentType.isEmpty()){
            throw new IllegalArgumentException("文件类型或文件名不能为空");
        }
        //检验MIME类型
        if(!ALLOWED_FILE_TYPES.contains(contentType)){
            return false;
        }
        //检验文件后缀名
        String fileExtension=getFileType(fileName);
        if(fileExtension==null||!ALLOWED_FILE_EXTENSIONS.contains(fileExtension.toLowerCase())){
            return false;
        }
        return true;
    }


    /**
     * 获取文件的扩展名
     * @param fileName 文件名
     * @return 扩展名
     */
    public static String getFileType(String fileName){
        int index = fileName.lastIndexOf(".");
        if(index >0 && index < fileName.length()-1){
            return fileName.substring(index+1);
        }
        return null;
    }
}

